import React from 'react';
import _ from 'underscore';
import {Scope} from './scopeFactory';

export default class View extends React.Component {
  constructor(props,context){
    super(props,context);

    if(this.props.Scope) {
      let scope = props.fetchAction && props.fetchAction();
      if (scope) {
        this.scope = scope;
        this.scope.__unbind = false;
      } else {
        this.scope = new this.props.Scope(props);
        this.scope.__loaded = false;
      }

      this.scope.viewInstance = this;
      this.state = this.scope.state();

      if (props.cacheAction) {
        props.cacheAction(this.scope);
      }
    }
  } // constructor

  getHandlerKey(){
   return location.hash;
 } // getHandlerKey

  componentDidMount() {
    if(this.scope){
      this.scope.bind(this);
    }
  } // componentDidMount

  componentWillReceiveProps(nextProps) {
    if (this.scope) {
      this.scope.$receive(nextProps);
    }
  } // componentWillReceiveProps

  componentWillUnmount() {
    if(this.scope){
      this.scope.unbind(this);
    }
  } // componentWillUnmount
}

View.defaultProps = {
  Scope:Scope,
  cacheAction: null
}

View.contextTypes = {
  router: React.PropTypes.func
}
